/**
 * ---------------------------
 * Time: 2017/8/14 18:43.
 * Author: Cangshi
 * View: http://palerock.cn
 * ---------------------------
 */
define(['app', 'zepto', 'jscolor'], function (app, $, jscolor) {
    app.controller('setting', function ($scope, ObjectUtils, configService) {
        var thisColorSetting = ObjectUtils.sortingArrayByProperty($scope.$parent.colorSetting, 'baseLine', 1);
        $scope.thisColorSetting = ObjectUtils.cloneObject(thisColorSetting);
        $scope.initAll = function () {
            $scope.$parent.initConfig(function () {
                thisColorSetting = ObjectUtils.sortingArrayByProperty($scope.$parent.colorSetting, 'baseLine', 1);
                $scope.thisColorSetting = ObjectUtils.cloneObject(thisColorSetting);
                $scope.$digest();
                $scope.initColor();
            });
        };
        $scope.initColor = function () {
            jscolor.init();
            setTimeout(function () {
                var colors = $('input.color');
                for (var i = 0; i < colors.length; i++) {
                    colors[i].color.importColor();
                }
            }, 100);
        };

        $scope.addColorNode = function () {
            $.prompt('请填写该颜色节点对应的百分比（单位：%）',
                function (nodePercentStr) {
                    var nodePercent = parseInt(nodePercentStr);
                    if (Number.isNaN(nodePercent) || nodePercent < 0) {
                        $.alert('请正确的输入一个数字！');
                        return;
                    }
                    var baseLine = 0;
                    if (nodePercent < 1 && nodePercent >= 0) {
                        baseLine = nodePercent;
                    } else {
                        baseLine = nodePercent / 100;
                    }
                    var node = {
                        baseLine: baseLine,
                        colorCode: '#000'
                    };
                    $scope.thisColorSetting.push(node);
                    $scope.thisColorSetting = ObjectUtils.sortingArrayByProperty($scope.thisColorSetting, 'baseLine', 1);
                    $scope.$digest();
                    $scope.initColor();
                }
            );
        };
        $scope.deleteNode = function (index) {
            var node = $scope.thisColorSetting[index];
            $scope.thisColorSetting.splice(index, 1);
            $scope.initColor();
        };
        // 保存对颜色的修改
        $scope.saveColorEdit = function (msg) {
            configService.setColorConfig($scope.thisColorSetting, function (message) {
                $.alert(msg + '[' + message + ']', function () {
                    app.backEvent();
                });
                $scope.$parent.colorSetting = $scope.thisColorSetting;
            });
        };
    });
});